var canvas = document.getElementById("canvas");	// for some reazon canvas won't 	initialize														
var context;												// inside functions

var sprites;		//sprite objects array

var onclickListeners;
var onmousemoveListeners;

var stock;			//domino objects array
var humanHand; 	//domino objects array
var computerHand;	//domino objects array

var lineOfPlay;	//domino objects array heir

var title;
var startButton;

var isGameStarted;

window.onload = function() {	
	init();							
	gameLoop();
}

function init() {		
	
	initCanvas();
	
	initListeners();			
					
	initStock();		
			
	initTitle();
	
	initStartButton();	// Button must be initialized after stock,
								// its size is based on domino piece 
	isGameStarted = false;
	
	context.save();
	context.translate(0.5 * canvas.width - 2 * stock[0].sprite.height, 0.5 * canvas.height);
	context.rotate(+Math.PI / 4);
	context.translate(-0.5 * canvas.width + 2 * stock[0].sprite.height, -0.5 * canvas.height);			
}

function initListeners() {
	onclickListeners = new Array();
	onmousemoveListeners = new Array();
	
	canvas.addEventListener("click", onclick);
	canvas.addEventListener("mousemove", onmousemove, true);
}	

function initCanvas() {
	canvas = document.getElementById("canvas");
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	
	context = canvas.getContext("2d");		
	
	drawBackground();
}

function initTitle() {	
				
	var titleText = "DoMiNó";
	
	var titleWidth = 300;
	titlePos = new Vector2(0.5 * (canvas.width - 2.5 * titleWidth),
									0.6 * titleWidth);
									
	title = new TitleSprite(titleText,
									context, 
									titlePos.x,
	 								titlePos.y,	 																										
									300);
							
	title.rotate(-Math.PI / 2);									
	
	sprites.push(title);
}

function initStartButton() {
	
	var dominoWidth = stock[0].sprite.width;
	var buttonText = "jogar";
	var buttonWidth = dominoWidth * 5;
	var buttonHeight = dominoWidth * 2;
	
	var buttonPos = new Vector2(0.5 * (canvas.width -  buttonWidth),
										0);

	startButton = new ButtonSprite(buttonText, 
												context,												
												buttonPos.x, buttonPos.y,
												buttonWidth, buttonHeight,
												startGame);	
				
	sprites.push(startButton);
	onclickListeners.push(startButton);
	onmousemoveListeners.push(startButton);		
}		

function initStock() {
		
	stock = new Array();
	sprites = new Array();
	var pips = 6;

	var dominoWidth = 2 * canvas.width > canvas.height ?
							0.045 * canvas.height :
							0.09 * canvas.width;

	var marginX = 0.5 * (canvas.width - (dominoWidth * pips)) - dominoWidth;
	var marginY = 0.5 * (canvas.height - (2 * dominoWidth * pips)) - dominoWidth;

	var dominoPiece;
	var dominoSprite;
	
	for(var i = 0; i <= pips; i++) {
		for(var j = 0; j <= pips - i; j++) {
		
			dominoSprite = new DominoSprite(context,
														marginX + (dominoWidth * i),
														marginY + (2 * dominoWidth * j),
														dominoWidth,
														2 * dominoWidth,
														dominoClick,
														null,
														i + j,
														j);
			
			dominoPiece = new DominoPiece(i + j, j, dominoSprite);			
			sprites.push(dominoSprite);
			stock.push(dominoPiece);						
					
			onclickListeners.push(dominoSprite);
			onmousemoveListeners.push(dominoSprite);			
		}
	}
	
	stock.shuffle();	
}

function gameLoop() {

	update();
	requestAnimationFrame(gameLoop);
	draw();
}

function update() {
	
	
}

function draw() {

	drawBackground();							
		
	for(var i = 0; i < sprites.length; i++) {
		sprites[i].draw();
	}	
		
}

function drawBackground() {
	context.fillStyle = "#558855";
	context.fillRect(0, 0, canvas.width, canvas.height);
	
	if(isGameStarted) {	
		context.fillStyle = "#000000";
		context.fillRect(lineOfPlay.topLeft.x, lineOfPlay.topLeft.y, 
								lineOfPlay.bottomRight.x - lineOfPlay.topLeft.x,
								lineOfPlay.bottomRight.y - lineOfPlay.topLeft.y);
	}	
	
}

function startGame() {
	context.restore();
	isGameStarted = true;	
				
	initStock();
	
	deliverPieces();
	
	humanPiece = humanHand[0];
	computerPiece = computerHand[0];
	stockPiece = stock[0];
	
	var topLeftBounds = new Vector2(0.5 * computerPiece.sprite.width, 
											computerPiece.sprite.position.y + computerPiece.sprite.height + 
												0.5 * computerPiece.sprite.width);

	var bottomRightBounds = new Vector2(stockPiece.sprite.position.x - 0.5 * stockPiece.sprite.width,
												humanPiece.sprite.position.y - 0.5 * humanPiece.sprite.width);
										
	lineOfPlay = new LineOfPlay(topLeftBounds, bottomRightBounds);
		
	lineOfPlay.unshift(find(6,3));
	lineOfPlay.unshift(find(6,2));
	lineOfPlay.unshift(find(2,0));
	lineOfPlay.unshift(find(4,0));
	lineOfPlay.unshift(find(4,4));
	lineOfPlay.unshift(find(4,2));

	lineOfPlay.unshift(find(2,2));					
}

function deliverPieces() {

	humanHand = new Array();
	computerHand = new Array();	
	
	var humanDomino;
	var computerDomino;		
	
	for(var i = 0; i < 7; i++) {
		
		humanDomino = stock.pop();
		computerDomino = stock.pop();;
		
		humanHand.push(humanDomino);
		computerHand.push(computerDomino);
	
		humanDomino.sprite.move(0.5 * (canvas.width - (7 * humanDomino.sprite.width)) +
													(i * humanDomino.sprite.width),
													
										canvas.height - (1.5 * humanDomino.sprite.height));

		computerDomino.sprite.setTurnedUp(false);
		onmousemoveListeners.remove(computerDomino.sprite);
		onclickListeners.remove(computerDomino.sprite);
		computerDomino.sprite.move(0.5 * (canvas.width - (7 * humanDomino.sprite.width)) + 
														(i * humanDomino.sprite.width),
													
											0.5 * humanDomino.sprite.height);		
	}
	
	placeStockSprites();
}

function placeStockSprites() {
	
	var dominoWidth = stock[0].sprite.width;
	var dominoHeight = stock[0].sprite.height;

	var pips = 6;
	var cols = 3;

	var marginX = canvas.width - 4 * dominoWidth;
	var marginY = 0.5 * (canvas.height - (dominoHeight * (stock.length / cols)));
	
	var dominoPiece;
	for(var i = 0; i < stock.length / cols; i++) {
		for(var j = 0; j < cols; j++) {
				
			// Workaround for the last iteration, 
			// that tries acessing a non-existent
			// stock piece
			 
			if(stock.length > (i + 1) * (j + 1)) {							
						
				dominoPiece = stock[(i * cols) + j];
				
				dominoPiece.sprite.move(marginX + (dominoPiece.sprite.width * j),
												marginY + (dominoPiece.sprite.height * i));			
							
				dominoPiece.sprite.setTurnedUp(false);				
			}
		
		}
		
	}
	
}

function dominoClick(source) {
	
	if(!isGameStarted) {
		sprites.remove(source);
		onclickListeners.remove(source);
		onmousemoveListeners.remove(source);
	}
	
	else {
								
		var hasPlayed = humanMove(source);
			
		if(hasPlayed) {				
			//computerMove();					
		}
	}
}

function humanMove(pieceSprite) {
	
					
	var piece;	
	
	for(var i = 0; i < humanHand.length; i++) {
		
		piece = humanHand[i];			
		if(piece.sprite == pieceSprite) {					
									
			if(lineOfPlay.isTop(piece)) {
							
				lineOfPlay.unshift(piece);			
				humanHand.remove(piece);
				removeOnMouseMoveListener(piece);
				onclickListeners.remove(piece);
				
				return true;			
			}	
		}	
	}
	
	for(var i = 0; i < stock.length; i++) {	
		if(stock[i].sprite == pieceSprite) {
			takePiece(humanHand, i);
			break;
		}
	}		

	return false;		
}

function computerMove() {
	
	var hasPlayed = false;
	var piece;
	
	for(var i = 0; i < computerHand.length; i++) {
			
		piece = computerHand[i];		
							
		if(lineOfPlay.isTop(piece)) {
			computerHand.remove(piece);
			lineOfPlay.unshift(piece);
			hasPlayed = true;			
			break;		
		}					
	}

	if(!hasPlayed) {	
		takePiece(computerHand, stock.length - 1);
		computerMove();
	}
}

function takePiece(hand, i) {
	
	var handPosition = new Vector2(hand.tail().sprite.position.x + hand.tail().sprite.width,
												hand.tail().sprite.position.y);	
	
	var takenPiece = stock[i];
	stock.remove(takenPiece); 	
	hand.push(takenPiece);					 
		
	takenPiece.sprite.move(handPosition);
	
	if(hand === humanHand) {
		takenPiece.sprite.setTurnedUp(true);
	}								
}


function removeOnMouseMoveListener(sprite) {
	
	sprite.setHovered(false);
	onmousemoveListeners.remove(sprite);
}

function onclick(e) {
	
	for(var i = 0; i < onclickListeners.length; i++) {
		onclickListeners[i].onclick(e);		
	}
	
}

function onmousemove(e) {
	
	for(var i = 0; i < onmousemoveListeners.length; i++) {

		onmousemoveListeners[i].onmousemove(e);
	}
	
}

function find(topPips, bottomPips) {
	
	for(var i = 0; i < stock.length; i++) {
		
		if(stock[i].topPips == topPips &&
			stock[i].bottomPips == bottomPips) { return stock[i]; } 
	}

	for(var i = 0; i < computerHand.length; i++) {
		
		if(computerHand[i].topPips == topPips &&
			computerHand[i].bottomPips == bottomPips) { return computerHand[i]; } 
	}

	for(var i = 0; i < humanHand.length; i++) {
		
		if(humanHand[i].topPips == topPips &&
			humanHand[i].bottomPips == bottomPips) { return humanHand[i]; } 
	}

	return null;		
}
